package com.example.demo.Controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.domain.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Spring MVC Controller
 * 1、查询所有的符合条件的用户信息，并分页传送给界面
 * 2、编辑方法从数据库中查询需要的数据
 * 3、存储方法把新增的用户或编辑后用户信息存储到数据库中
 * 4、删除用户
 * 5、锁定用户、有效状态
 *
 * @author xue
 */

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 根据条件查询用户信息
     *
     * @param kw       查询关键字即条件
     * @param model    模型对象，也是视图（界面）的上下文环境对象
     * @param pageable 分页信息对象，包含了分页需要的基本信息，如当前页码，每页需要的条数
     * @return 字符串代表了界面文件
     */
    @RequestMapping("/listusers")
    public String list(String kw, Model model, Pageable pageable) {
        if (kw!=null)kw="%"+kw+"%";
        if (kw==null)kw="%%";
        Page<User> ppu = userService.findAll(kw, pageable);//默认分页从第0页面（第一页），取每页20条数据
        model.addAttribute("pages", ppu);
        return "listusers";//返回界面
    }

    @GetMapping({"/editusers", "/editusers/{uid}"})
    public String edit(@PathVariable(name = "uid", required = false) Integer uid, Model model) {
        User u = new User();
        if (uid != null && uid > 0) {
            u = userService.findById(uid);
        }
        model.addAttribute("user", u);
        return "editusers";
    }

    @PostMapping("/saveuser")
    public String save(@Valid User user, BindingResult result) {
        try {
            if (result.hasErrors()) {
                return "redirect:/editusers";
            }
            userService.save(user);
            return "redirect:/listusers";
        }catch (Exception ex){
            return "redirect:/editusers";
        }
    }

    @GetMapping("/delete/{uid}")
    public String delete(@PathVariable("uid") Integer uid) {
        userService.deletetById(uid);
        return "redirect:/listusers";
    }

    @GetMapping("/deletes/{uids}")
    public String deletes(@PathVariable("uids") String uids) {
        List<User> users = new ArrayList<>();
        JSONObject json = JSONObject.parseObject(uids);
        JSONArray arr = json.getJSONArray("uids");//前端传递时使用json数据的键
        int ilen = arr.size();
        for (int i = 0; i < ilen; i++) {//每次循环ilen次来执行ilen个查询，再去删除
            users.add(userService.findById(arr.getInteger(i)));
        }
        userService.deletes(users);
        return "redirect:/listusers";
    }

    @GetMapping("/validuser/{uid}")
    public String validuser(@PathVariable("uid") Integer uid) {
        User user = userService.findById(uid);
//        if (user.getValidstate()==0)user.setValidstate(1);//当无效时设置为有效
//        if (user.getValidstate()==1)user.setValidstate(0);//当有效时设置为无效
//        简单的设置语句
        user.setValidstate(1 - user.getValidstate());
        return "redirect:/listusers";
    }
}
